<template>
  <div class="wrapper">
    <el-card>
      <div class="rowDiv" style="padding: 0; justify-content: flex-end">
        <el-button type="primary" @click="createDepartment()"
          >创建部门
        </el-button>
      </div>
      <!-- 页面加载 -->
      <el-table
        class="text-center"
        :data="state.tableData"
        :align="center"
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="id" label="部门ID" width="100"></el-table-column>
        <el-table-column prop="name" label="部门名称"></el-table-column>
        <el-table-column prop="creator_name" label="创建人"> </el-table-column>
        <el-table-column prop="leader_name" label="部门负责人">
        </el-table-column>
        <el-table-column prop="parent_department_name" label="上级部门">
        </el-table-column>
        <el-table-column prop="add_time" label="创建时间"></el-table-column>
        <el-table-column prop="staff_count" label="部门人数"></el-table-column>
        <el-table-column label="绑定门店数量">
          <template v-slot="scope">
            <el-button @click="has_store(scope)" type="text">{{
              scope.row.store_count
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="全门店绑定">
          <template v-slot="scope">
            <div @click="change_Switch($event, scope.row)">
              <el-switch
                v-model="scope.row.all_store"
                :active-value="1"
                :inactive-value="0"
                active-text="开"
                inactive-text="关"
                active-color="#13ce66"
                inactive-color="#ff4949"
              ></el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              @click.native.prevent="bind_store(scope.row)"
              type="text"
              size="small"
            >
              绑定门店
            </el-button>
            <el-button
              @click.native.prevent="edit_depart(scope.row)"
              type="text"
              size="small"
            >
              编辑
            </el-button>
            <el-button
              @click.native.prevent="deleteRow(scope.row)"
              type="text"
              size="small"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
       <Page v-if="state.all_page" :totalPage="state.all_page" @changePage="changePage"></Page>
      <!-- 创建部门 -->
      <el-dialog
        :title="state.good_title"
        v-model="state.depart_dialogVisible"
        width="18%"
        center
      >
        <span>
          <el-form
            :model="state.form"
            :rules="state.rules"
            ref="form"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="部门名称" prop="department_name">
              <el-input
                type="text"
                v-model="state.form.department_name"
              ></el-input>
            </el-form-item>
            <el-form-item label="上级部门" prop="up_charge">
              <el-select
                type="date"
                placeholder="请选择"
                filterable
                @change="change_up_charge"
                v-model="state.form.up_charge"
                style="width: 100%"
              >
                <template v-for="child in state.up_chargeArr" :key="child.id">
                  <el-option :value="child.id" :label="child.name"></el-option>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="负责人" prop="charge_man">
              <el-select
                type="date"
                placeholder="请选择"
                filterable
                @change="change_charge_man"
                v-model="state.form.charge_man"
                style="width: 100%"
              >
                <template v-for="child in state.charge_manArr" :key="child.id">
                  <el-option
                    :value="child.id"
                    :label="child.username"
                  ></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-form>
        </span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="state.depart_dialogVisible = false"
              >取 消</el-button
            >
            <el-button type="primary" @click="create()">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 抽屉组件 -->
      <Drawer
        :title="state.current_title"
        :drawer="state.drawer"
        @closeFun="closeFun"
      >
        <!-- 作用域插槽 -->
        <!-- 地区 运营  搜索 -->
        <template v-slot:form_option>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="row-item">
                <div>地区:</div>
                <el-select
                  clearable
                  v-model="state.address"
                  @change="commonChange"
                  placeholder="选择地区"
                >
                  <template v-for="item in state.addressArr">
                    <el-option :label="item.name" :value="item.id"></el-option>
                  </template>
                </el-select>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="row-item">
                <div>客户经理:</div>
                <el-select
                  clearable
                  v-model="state.custom"
                  @change="commonChange"
                  placeholder="选择客户经理"
                >
                  <template v-for="item in state.customArr">
                    <el-option :label="item.name" :value="item.id"></el-option>
                  </template>
                </el-select>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="row-item">
                <div>运营经理:</div>
                <el-select
                  clearable
                  v-model="state.sport"
                  @change="commonChange"
                  placeholder="选择运营经理"
                >
                  <template v-for="item in state.sportArr">
                    <el-option :label="item.name" :value="item.id"></el-option>
                  </template>
                </el-select>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="row-item">
                <el-input
                  clearable
                  type="text"
                  v-model="state.keyword"
                ></el-input>
                <el-button type="primary" @click="onSubmit">查询</el-button>
              </div>
            </el-col>
          </el-row>
        </template>
        <!-- 已绑定的内容 -->
        <template v-slot:look_store v-if="state.is_show_type">
          <el-table
            class="text-center"
            :data="state.already_store"
            ref="multipleTable"
            max-height="500"
            @selection-change="handleSelectionChange"
            :align="center"
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="store_id" label="部门ID"></el-table-column>
            <el-table-column
              prop="store_num"
              label="门店编号"
            ></el-table-column>
            <el-table-column prop="store_name" label="门店名称">
            </el-table-column>
            <el-table-column prop="boss_name" label="掌柜"></el-table-column>
            <el-table-column prop="area" label="地区"> </el-table-column>
            <el-table-column prop="manager_name" label="客户经理">
            </el-table-column>
            <el-table-column prop="operations_name" label="运营经理">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  @click.native.prevent="unbindBtn(scope.row)"
                  type="text"
                  size="small"
                >
                  解绑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="rowDiv" style="width: 20%">
            <el-col :span="3">
              <el-checkbox
                @change="checkAll"
                v-model="state.pageChecked"
                label="本页全选"
                name="type"
              ></el-checkbox>
            </el-col>
            <el-button @click="unbind_all_Btn">解绑</el-button>
          </div>
        </template>
        <!-- 绑定的内容 -->
        <template v-slot:bind_store v-else>
          <el-table
            class="text-center"
            :data="state.storeData"
            :align="center"
            ref="multipleTable"
            max-height="500"
            @selection-change="handleSelectionChange"
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="store_id" label="部门ID"></el-table-column>
            <el-table-column
              prop="store_num"
              label="门店编号"
            ></el-table-column>
            <el-table-column prop="store_name" label="门店名称">
            </el-table-column>
            <el-table-column prop="boss_name" label="掌柜"> </el-table-column>
            <el-table-column prop="area" label="地区"> </el-table-column>
            <el-table-column prop="manager_name" label="客户经理">
            </el-table-column>
            <el-table-column prop="operations_name" label="运营经理">
            </el-table-column>
          </el-table>
          <div class="rowDiv">
            <el-col :span="6">
              <el-checkbox
                @change="checkAll"
                v-model="state.pageChecked"
                label="本页全选"
                name="type"
              ></el-checkbox>
              <!-- <el-checkbox
                @change="checkAll"
                v-model="state.all_store_check"
                label="全门店"
                name="type"
              ></el-checkbox> -->
            </el-col>
            <el-col :span="6">
              <Page v-if="state.store_all_page" :totalPage="state.store_all_page" @changePage="bind_page_fun"></Page>
            </el-col>
          </div>
          <div class="btnGroup">
            <el-button @click="state.drawer = false">取消</el-button>
            <el-button type="primary" @click="bind_sub">绑定</el-button>
          </div>
        </template>
      </Drawer>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, getCurrentInstance, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElNotification } from "element-plus";
import Drawer from "@/components/Drawer.vue";
import Page from "@/components/Pagination.vue";

export default {
    name:"department_manager",
  components: {
    Drawer,
    Page,
  },
  setup() {
    let form = ref(null);
    let multipleTable = ref(null);
    const { ctx } = getCurrentInstance();
    let router = useRouter();
    let state = reactive({
      common_type: "",
      current_title: "",
      is_show_type: true, //是否显示绑定门店还是查看已绑定门店
      keyword: "",
      addressArr: [],
      customArr: [],
      sportArr: [],
      address: "",
      custom: "",
      sport: "",
      common_id: "",
      page: 1,
      all_page: 1,
      drawer: false,
      store_page:1, //绑定门店的页码
      store_all_page:1,//绑定门店的总页码
      // all_store_check: false, //全门店
      pageChecked: false, //全选切换状态
      saveCheckList: [],
      multipleSelection: [], //绑定表格
      depart_dialogVisible: false,
      is_open: false,
      form: {
        department_name: "",
        up_charge: "",
        charge_man: "",
      },
      rules: {
        department_name: [
          { required: true, message: "请填写部门名称", trigger: "blur" },
        ],
        up_charge: [
          { required: true, message: "请选择上级部门", trigger: "change" },
        ],
        charge_man: [
          { required: true, message: "请选择负责人", trigger: "change" },
        ],
      },
      up_chargeArr: [],
      charge_manArr: [],
      tableData: [],
      already_store: [], //已绑定门店数据
      storeData: [], //获取绑定门店数据
      unbind_temp: [], //解绑暂存数据
    });
    onMounted(() => {
      getOrderlist();
      get_up_depart();
      get_charge_man();
      get_common();
    });
    // 触发已绑定门店弹窗
    function has_store(item) {
      clearSelect();
      state.common_id = item.row.id;
      state.current_title = "已绑定门店";
      state.is_show_type = true;
      has_bind_store();
      state.drawer = true;
    }
    // 触发绑定门店弹窗
    function bind_store(item) {
      clearSelect();
      state.common_id = item.id;
      getStorelist();
      state.drawer = true;
      state.is_show_type = false;
      state.current_title = "绑定门店";
    }
    // 获取已绑定门店信息
    function has_bind_store() {
      ctx.$http
        .get("/tanxiaji/position/staff/store_mange/list/", {
          id: state.common_id,
          data_type: 10,
          area_id: state.address,
          manager_id: state.custom,
          operations_id: state.sport,
          keywords: state.keyword,
        })
        .then((res) => {
          if (res.errno == 0) {
            state.already_store = res.data.data_list;
            state.store_all_page = res.data.all_page;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 公共清空下拉所选中的数据
    function clearSelect() {
      state.page = 1;
      state.keyword = "";
      state.address = "";
      state.custom = "";
      state.sport = "";
      state.multipleSelection = [];
      state.pageChecked = false;
    }
    // 批量解绑
    function unbind_all_Btn() {
      state.unbind_temp = [];
      console.log("已勾选的", state.multipleSelection);
      state.multipleSelection.forEach((v) =>
        state.unbind_temp.push(v.store_id)
      );
      if (!state.unbind_temp.length)
        return ElNotification.error("请勾选再进行操作");
      common_unbindFun();
    }
    // 单一解绑
    function unbindBtn(item) {
      state.unbind_temp = [];
      state.unbind_temp.push(item.store_id);
      common_unbindFun();
    }
    // 公共解绑方法
    function common_unbindFun() {
      ctx.$http
        .post("/tanxiaji/position/staff/store_mange/remove/", {
          store_id_list: JSON.stringify(state.unbind_temp),
          obj_id: state.common_id,
          data_type: 10, //1 员工 10 部门
        })
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            has_bind_store();
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    //公共改变
    function commonChange() {
      if (state.is_show_type) {
        has_bind_store();
      } else {
        getStorelist();
      }
    }
    function onSubmit() {
      // true 是已绑定门店
      if (state.is_show_type) {
        has_bind_store();
      } else {
        getStorelist();
      }
    }

    //   创建部门
    function createDepartment() {
      state.common_type = "创建";
      state.depart_dialogVisible = true;
      form.value.resetFields();
      state.form.department_name = "";
      state.form.up_charge = "";
      state.form.charge_man = "";
    }

    // 删除部门
    function deleteRow(item) {
      if (confirm("是否要删除?")) {
        ctx.$http
          .post("/tanxiaji/position/department/del/", {
            id: item.id,
          })
          .then((res) => {
            if (res.errno == 0) {
              ElNotification.success(res.errmsg);
              getOrderlist();
            } else {
              ElNotification.error(res.errmsg);
            }
          })
          .catch((err) => {
            ElNotification.error(err);
          });
      }
    }

    //获取列表
    function getOrderlist() {
      ctx.$http
        .get("/tanxiaji/position/department/data_list/", { index: state.page })
        .then((res) => {
          if (res.errno == 0) {
            state.tableData = res.data.data_list;
            state.all_page=res.data.all_page;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    // 编辑部门
    function edit_depart(item) {
      let par_name = item.parent_department_name;
      let leader = item.leader_name;
      state.current_title = "绑定门店";
      state.common_id = item.id;
      state.common_type = "编辑";
      state.depart_dialogVisible = true;
      state.form.department_name = item.name;
      state.form.up_charge = state.up_chargeArr.find(
        (v) => v.name == par_name
      ).id;
      state.form.charge_man = state.charge_manArr.find(
        (v) => v.username == leader
      ).id;
    }

    // 获取上级部门
    function get_up_depart() {
      ctx.$http
        .get("/tanxiaji/position/department/data/")
        .then((res) => {
          state.up_chargeArr = res.data;
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    // 获取负责人
    function get_charge_man() {
      ctx.$http
        .get("/tanxiaji/get_user_list/", {
          count: 1000,
          job_id: "",
          department_id: "",
          keywords: "",
        })
        .then((res) => {
          state.charge_manArr = res.user_list;
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    //    提交部门
    function create() {
      let url = "";
      let data = "";
      if (state.common_type == "创建") {
        url = "/tanxiaji/position/department/create/";
        data = {
          name: state.form.department_name,
          parent: state.form.up_charge,
          director: state.form.charge_man,
        };
      } else {
        url = "/tanxiaji/position/department/edit/";
        data = {
          name: state.form.department_name,
          parent: state.form.up_charge,
          director: state.form.charge_man,
          pk: state.common_id,
        };
      }
      form.value.validate((valid) => {
        if (valid) {
          ctx.$http
            .post(url, data)
            .then((res) => {
              if (res.errno == 0) {
                ElNotification.success(res.errmsg);
                state.depart_dialogVisible = false;
                getOrderlist();
              } else {
                ElNotification.error(res.errmsg);
              }
            })
            .catch((err) => {
              ElNotification.error(err);
            });
        } else {
        }
      });
    }

    // 关闭弹窗
    function closeFun(e) {
      console.log("来自子组件", e);
      state.drawer = e;
    }
    //表格选择
    function handleSelectionChange(val) {
      state.multipleSelection = val;
    }
    //全选
    function checkAll() {
      state.multipleSelection = [];
      if (state.pageChecked) {
        multipleTable.value.toggleAllSelection();
        state.multipleSelection.push(state.tableData.filter((v) => v.id));
      } else {
        multipleTable.value.clearSelection();
        state.multipleSelection = [];
      }
    }
    //绑定门店页数
    function bind_page_fun(e){
      state.store_page = e;
      getStorelist();
    }
    // 页面列表
    function changePage(e) {
      state.page=e;
      getOrderlist();
    }
    //获取绑定门店数据
    //获取列表
    function getStorelist() {
      ctx.$http
        .get("/tanxiaji/position/staff/store_mange/usable_list/", {
          index: state.store_page,
          count: 1000,
          id: state.common_id,
          data_type: 10, //员工1 部门10
          area_id: state.address,
          manager_id: state.custom,
          operations_id: state.sport,
          keywords: state.keyword,
        })
        .then((res) => {
          if (res.errno == 0) {
            state.storeData = res.data.data_list;
            state.store_all_page = res.data.all_page;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    //绑定提交
    function bind_sub() {
      let ids = [];
      state.multipleSelection.forEach((v) => ids.push(v.store_id));
      console.log(ids);
      if (!ids.length) return ElNotification.error("请勾选后在进行操作");
      ctx.$http
        .post("/tanxiaji/position/staff/store_mange/add/", {
          store_id_list: JSON.stringify(ids),
          obj_id: state.common_id,
          data_type: 10, //1 员工 10 部门
        })
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            state.drawer = false;
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 修改开关
    function change_Switch(e, data) {
      ctx.$http
        .post("/tanxiaji/position/department/store_switch/", {
          id: data.id,
        })
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            getOrderlist();
          } else {
            getOrderlist();
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    //公用地区等下载
    function get_common() {
      ctx.$http
        .get("/tanxiaji/customer/selection/")
        .then((res) => {
          if (res.errno == 0) {
            state.addressArr = res.data.area_list;
            state.customArr = res.data.sale_manager_list;
            state.sportArr = res.data.run_manager_list;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    return {
      has_store,
      commonChange,
      onSubmit,
      get_common,
      bind_sub,
      changePage,
      checkAll,
      handleSelectionChange,
      multipleTable,
      form,
      state,
      getOrderlist,
      createDepartment,
      create,
      edit_depart,
      deleteRow,
      bind_store,
      closeFun,
      unbind_all_Btn,
      unbindBtn,
      change_Switch,
    };
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  .rowDiv {
    display: flex;
    align-items: center;
    padding: 10px 0;
    justify-content: space-between;
  }
  .row-item {
    display: flex;
    white-space: nowrap;
    align-items: center;
  }
  .btnGroup {
    width: 30%;
    margin: 20px auto;
    display: flex;
    justify-content: space-between;
  }
  .el-table /deep/ th {
    background-color: #eaeaea;
    text-align: center;
  }
  .el-table /deep/ td {
    text-align: center;
  }
}
</style>